#include "lessoncreation.h"
#include "ui_lessoncreation.h"
#include "listitem.h"
#include "phrasecreator.h"
#include "includes/phrase.h"
#include <QIcon>
#include <QFileDialog>
#include <QDesktopServices>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <iostream>
#include <QDir>

LessonCreation::LessonCreation(QWidget *parent) :
    QWidget(parent),
    l_ui(new Ui::LessonCreation)
{
    l_ui->setupUi(this);
    addFiles("xml/");
}

void LessonCreation::clear()
{
    l_ui->lessonName->setText("");
    l_ui->lessonDescription->setText("");
    l_ui->lessonDifficulty->setCurrentIndex(1);

    added.clear();
    l_ui->loadedListWid->clear();
    l_ui->selectedListWid->clear();

    l_ui->lessonIconButton->setIcon(QIcon());
    l_ui->lessonIconButton->setText("Select Icon");
    temp.setIcon("");
    addFiles("xml/");
}

/*
this function creates a dialog where the user selects the videos
that they would like in the lesson the selected videos are then
added to a qlist, a check is run to see if the list already has
a video in it if it does the video is not added again
*/
void LessonCreation::addFiles(QString fileOrPath)
{
    PhraseCollection pc;
    pc.fromXML(fileOrPath);

    foreach (Phrase ph, pc)
    {
        if (added.contains(ph)) continue;
        added.append(ph);
        l_ui->loadedListWid->addItem(
                new ListItem(ph, l_ui->loadedListWid));
    }
}

void LessonCreation::createPhrase()
{
    PhraseCreator PC(this);
    Phrase ph = PC.getPhrase();
    QDomDocument root;
    if (ph.getName() == "") return;
    ph.saveToChild(root);

    QString filename(QString("xml/").append(
            ph.getName().replace(QRegExp("[^a-zA-Z0-9_ ]"),"").replace(QRegExp("\\s+"),"_").append(".xml")));

    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    QTextStream stream(&file);
    root.save(stream,0);

    addFiles(filename);
}

void LessonCreation::editPhrase()
{
    QListWidgetItem* item = 0;
    if (l_ui->loadedListWid->selectedItems().size() == 1)
        item = l_ui->loadedListWid->currentItem();
    else if (l_ui->selectedListWid->selectedItems().size() == 1)
        item = l_ui->selectedListWid->currentItem();

    if (item == 0)
        return;
    Phrase p = ((ListItem*)item)->getPhrase();
    PhraseCreator pc (this, p);
    p = pc.getPhrase();
    if (p.getName() != "")
    {
        ((ListItem*)item)->setPhrase(p);
        QDomDocument root;
        p.saveToChild(root);
        QString filename(QString("xml/").append(
                p.getName().replace(QRegExp("[^a-zA-Z0-9_ ]"),"").replace(QRegExp("\\s+"),"_").append(".xml")));

        QFile file(filename);
        file.open(QIODevice::WriteOnly);
        QTextStream stream(&file);
        root.save(stream,0);
    }
}


void LessonCreation::deletePhrase()
{
    QListWidgetItem* item = 0;
    if (l_ui->loadedListWid->selectedItems().size() == 1)
        item = l_ui->loadedListWid->currentItem();
    else if (l_ui->selectedListWid->selectedItems().size() == 1)
        item = l_ui->selectedListWid->currentItem();

    if (item == 0)
        return;

    Phrase p = ((ListItem*)item)->getPhrase();
    QDir dir;
    dir.remove(QString("xml/").append(
            p.getName().replace(QRegExp("[^a-zA-Z0-9_ ]"),"").replace(QRegExp("\\s+"),"_").append(".xml")));
    delete item;
}

void LessonCreation::selectIcon()
{

    QString fname;
    fname = QFileDialog::getOpenFileName(
            this,
            tr("Open Icon"),
            QString("icons/"),
            tr("Images (*.png *.xpm *.jpg)"));
    if (fname == "") return;

    l_ui->lessonIconButton->setIcon(QIcon(fname));
    l_ui->lessonIconButton->setText(0);
    l_ui->lessonIconButton->setIconSize(QSize(90,90));
    temp.setIcon(QDir("icons/").relativeFilePath(fname));
}

void LessonCreation::outsideAction(QAction *action)
{
    if (action->text() == "Create Lesson")
        this->clear();

    else if (action->text() == "Save Lesson")
        this->saveLesson();

    else if (action->text() == "Delete Lesson")
        this->clear();

    else if (action->text() == "Edit Phrase")
        this->editPhrase();

    else if (action->text() == "Create Phrase")
        this->createPhrase();

    else if (action->text() == "Delete Phrase")
        this->deletePhrase();
}

/*
this function is used to load already made lessons so that they can be edited
*/
void LessonCreation::loadLesson(Lesson toLoad)
{
    this->clear();

    l_ui->lessonName->setText(toLoad.getName());
    l_ui->lessonDescription->setText(toLoad.getDescription());
    l_ui->lessonDifficulty->setCurrentIndex(toLoad.getDifficulty());
    l_ui->lessonIconButton->setIcon(QIcon(QString("icons/")+toLoad.getIcon()));
    l_ui->lessonIconButton->setIconSize(QSize(90,90));
    temp.setIcon(toLoad.getIcon());
    this->shiftAllLeft();

    foreach (Phrase p, toLoad)
    {
        if (added.contains(p))
        {
            QList<QListWidgetItem*> list(l_ui->loadedListWid->findItems(
                    QString(p.getName()), Qt::MatchFixedString)); //creating a QListeWidgetItem for each filename
            foreach (QListWidgetItem* wi, list)
            {
                l_ui->loadedListWid->setCurrentItem(wi); //loading the list item
                l_ui->loadedListWid->takeItem(l_ui->loadedListWid->currentRow()); //getting the next list item

                l_ui->selectedListWid->addItem(wi); //adding an item to the list
                //std::cout << wi->text().toStdString() << std::endl;
            }
            continue;
        }
        else {
            added.append(p);
            l_ui->selectedListWid->addItem(new ListItem(p, l_ui->selectedListWid));
        }
    }
}

/*
this function save the selected videos address to a file with the name of the lesson
*/
void LessonCreation::saveLesson()
{
    QString lessonName = QString("lessons/").append(l_ui->lessonName->text())
                         .append(".xml");
    QFile file(lessonName);
    
    if (l_ui->lessonName->text() == "")
        return;

    int ret = QMessageBox::Save;
    if (file.exists(lessonName)) //check to see if the file exists
    {
        QMessageBox msgBox;
        msgBox.setText("The lesson you selected already exists.");
        msgBox.setInformativeText("Do you want to overwrite it?");
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        ret = msgBox.exec();
    }
    
    switch (ret) {
    case QMessageBox::Save:
        if (file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text))
        {
            temp.setName(l_ui->lessonName->text());
            temp.setDescription(l_ui->lessonDescription->toPlainText());
            temp.setDifficulty(l_ui->lessonDifficulty->currentIndex());
            for (int i = 0; i < l_ui->selectedListWid->count(); i++)
                temp << (((ListItem*)l_ui->selectedListWid->item(i))->getPhrase());
            temp.toXML(lessonName);
            emit changedLesson(temp);
        }
       break;
    case QMessageBox::Discard://id the discard button is clicked
       break;
    case QMessageBox::Cancel://if the cancel button is clicked
       return;
    default:
       // should never be reached
       break;
    }
}

LessonCreation::~LessonCreation()
{
    delete l_ui;
}

/*
this function is created by QT
*/
void LessonCreation::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        l_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

/*
this function is used to shift a single video from the left hand ;list view to the right hand one
*/
void LessonCreation::shiftRight()
{
    ListItem* item = (ListItem*)l_ui->loadedListWid->takeItem(l_ui->loadedListWid->currentRow());
    l_ui->selectedListWid->addItem(item);
    l_ui->loadedListWid->clearSelection();
    l_ui->selectedListWid->setCurrentItem(item);
}
/*
this function is used to shifts all the videso to the selected videos view
*/
void LessonCreation::shiftAllRight()
{
    while (l_ui->loadedListWid->count() > 0) //while loop runs aslong as there are videos to be moved
        l_ui->selectedListWid->addItem(l_ui->loadedListWid->takeItem(0));
}
/*
this function shifts a video from the selected videos list to the available videos list
*/
void LessonCreation::shiftLeft()
{
    ListItem* item = (ListItem*)l_ui->selectedListWid->takeItem(l_ui->selectedListWid->currentRow());
    l_ui->loadedListWid->addItem(item);
    l_ui->selectedListWid->clearSelection();
    l_ui->loadedListWid->setCurrentItem(item);
}
/*
this function shifts all the videos from the selcted videos list to the available videos list
*/
void LessonCreation::shiftAllLeft()
{
    while (l_ui->selectedListWid->count() > 0) //same as shift All right
        l_ui->loadedListWid->addItem(l_ui->selectedListWid->takeItem(0));
}
